import React, { Component } from 'react'

export default class GoodsList extends Component {

    state = {
        val: '',
        list: [
            {
                name: '棒棒糖',
                count: 1,
                price: 19,


            },
            {
                name: '大鸡腿',
                count: 2,
                price: 9,


            },
            {
                name: '钟薛高',
                count: 1,
                price: 20,


            }
        ]
    }

    myFn = (val) => {
        console.log(val)
        this.setState({
            val
        })
    }

    myCount = (val, curItem) => {
        // alert(val)
        // console.log(curItem)
        // curItem.count += val
        const { list } = this.state
        list.forEach(item => {
            if (item.name === curItem.name) {
                item.count += val
            }
        })

        this.setState({
            list
        })


    }

    render () {

        const { list } = this.state
        return (
            <>

                <div>GoodsList----------  准备接受子组件的值：{this.state.val}</div>
                {
                    list.map(item => {
                        return <List item={item} fn={(data, cur) => this.myCount(data, cur)}></List>
                    })
                }

                <hr />

                {/* <ChildCom fn={(data) => this.myFn(data)}></ChildCom> */}


            </>

        )
    }
}


// function List ({ item: { name, count, price } }) {
//     // console.log()
//     return (
//         <>
//             <p>名字：{name}</p>
//             <p> 数量：{count} </p>
//             <p> 单价:{price}</p>
//             <p> 总价：{count * price}</p>
//             <hr />
//         </>

//     )


// }


function List (props) {
    function addCount () {
        props.fn(1, props.item)
    }

    return (
        <>
            <p>名字：{props.item.name}</p>
            <p> 数量：{props.item.count} </p>
            <p> 单价:{props.item.price}</p>
            <p> 总价：{props.item.count * props.item.price}</p>

            <button onClick={addCount}> 点击添加数量</button>
            <hr />
        </>

    )


}


class ChildCom extends React.Component {

    state = {
        msg: '花了老头的100块'
    }

    handlerClick = () => {
        this.props.fn(this.state.msg)
    }
    render () {
        console.log(this.props)
        return (
            <>
                <h1> 子组件 实现 子向父传值</h1>

                <button onClick={this.handlerClick}> 点击 调用父组件的函数</button>

                <button onClick={() => this.setState({ msg: '花50' })}>  改变msg</button>

            </>
        )
    }
}

